package com.practices2.util.bitmaptools;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.LinkedBlockingDeque;

import android.graphics.Bitmap;
import android.widget.ImageView;

/**
 * @author washpan 190848972@qq.com 用于加载bitmap的装载器
 * */
public class BitmapLoader {
	/**
	 * 当快速滑动时不加载
	 * */
	public static final Object LOCKWHENSCROLL = new Object();
	private BitmapLruCache cache = null;
	private boolean isPause = false;
	private String path = "";
	private int defaultWidth = 100;
	private int defaultHeight = 100;
	private boolean isStop = false;
	private Thread loadingThread = null;
	private ArrayList<LoadBitmapListener> listeners = new ArrayList<BitmapLoader.LoadBitmapListener>();
	/**
	 * 通过view找到正在执行的task,像listView重用item时快速滑动时旧的view所对应的task如果未启动就没有必要让其再启动了,
	 * 因为会很耗资源
	 * */
	private HashMap<ImageView, LoadingTask> views = new HashMap<ImageView, LoadingTask>();

	/**
	 * 加载锁队列
	 * */
	private LinkedBlockingDeque<LoadingTask> tasks = new LinkedBlockingDeque<BitmapLoader.LoadingTask>();

	class LoadingTask implements Runnable {
		private String url = "";
		private ImageView view = null;
		public boolean isWorking = false;

		public LoadingTask(String url, ImageView view) {
			this.url = url;
			this.view = view;
		}

		public boolean isStop = false;

		@Override
		public void run() {

			// 用于快速滑动时锁住加载操作
			synchronized (LOCKWHENSCROLL) {
				while (isPause) {
					try {
						LOCKWHENSCROLL.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			}
			// 此处加一下判断.不好意思,之前忘记了加上
			if (isStop) {
				return;
			}
			isWorking = true;
			// 先从本地加载
			SafeBitmap safeBitmap = loadLocal(url);
			if (null != safeBitmap && null != safeBitmap.bitmap) {
				// 放入缓存中
				synchronized (cache) {
					cache.put(NameUtils.generateKey(url), safeBitmap);
				}

				synchronized (listeners) {
					for (LoadBitmapListener l : listeners) {
						l.onFinish(view, safeBitmap.bitmap);
					}
				}
			}
			// 从网络加载
			else {
				HttpDownloadPic dowload = new HttpDownloadPic();
				File cacheFile = new File(path, NameUtils.generateKey(url));
				try {
					dowload.downloadPic(cacheFile, url);

					if (null != cacheFile && cacheFile.exists()) {
						safeBitmap = loadLocal(url);
						if (null != safeBitmap && null != safeBitmap.bitmap) {
							// 放入缓存中
							synchronized (cache) {
								cache.put(NameUtils.generateKey(url), safeBitmap);
							}
							synchronized (listeners) {
								for (LoadBitmapListener l : listeners) {
									l.onFinish(view, safeBitmap.bitmap);
								}
							}
						}
					} else {
						synchronized (listeners) {
							for (LoadBitmapListener l : listeners) {
								l.onError(view);
							}
						}
					}
				} catch (IOException e) {
					synchronized (listeners) {
						for (LoadBitmapListener l : listeners) {
							l.onError(view);
						}
					}
				} finally {
					synchronized (views) {
						views.remove(view);
					}
				}
			}

		}

	}

	public void setPause(boolean isPause) {
		this.isPause = isPause;
		if (!isPause) {
			synchronized (LOCKWHENSCROLL) {
				LOCKWHENSCROLL.notifyAll();
			}
		}
	}

	public BitmapLoader(BitmapLruCache cache, String path, int defaultWidth, int defaultHeight) {
		this.cache = cache;
		this.path = path;
		this.defaultWidth = defaultWidth;
		this.defaultHeight = defaultHeight;
		loadingThread = new Thread(new Worker());
		loadingThread.start();

	}

	public class Worker implements Runnable {
		public void run() {
			while (!isStop) {
				LoadingTask task = null;
				task = tasks.poll();
				if (null != task && !task.isStop) {
					task.run();
				}
			}
		}
	}

	public interface LoadBitmapListener {

		void onFinish(final ImageView view, final Bitmap bitmap);

		void onError(final ImageView view);
	}

	public synchronized void loadBitmap(final ImageView view, final String url, final LoadBitmapListener listener) {
		// 停掉之前的任务
		synchronized (views) {
			LoadingTask oldTask = views.get(view);
			if (null != oldTask && !oldTask.isWorking) {
				oldTask.isStop = true;
			}
		}

		synchronized (listeners) {
			listeners.add(listener);
		}
		LoadingTask task = new LoadingTask(url, view);
		synchronized (views) {
			views.put(view, task);
		}
		try {
			tasks.put(task);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 从本地加载图片
	 * */
	private SafeBitmap loadLocal(String url) {

		SafeBitmap safeBitmap = new SafeBitmap();
		safeBitmap.bitmap = BitmapDecodeTool.decodeBitmap(path + File.separator + NameUtils.generateKey(url), defaultWidth, defaultHeight, 3, Bitmap.Config.RGB_565, false);
		safeBitmap.config = Bitmap.Config.RGB_565;
		return safeBitmap;
	}

	public SafeBitmap getCahe(String key) {
		return this.cache.get(key);
	}

	public void cleanCache(boolean isRecycle) {
		this.cache.isRecycleWhenRemove = isRecycle;
		this.cache.evictAll();
		this.isStop = true;
		synchronized (views) {
			views.clear();
		}
		synchronized (listeners) {
			listeners.clear();
		}
	}
}
